<template>
  <div class="checkout-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/cart' }">购物车</el-breadcrumb-item>
        <el-breadcrumb-item>确认订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">确认订单</h1>
    </div>
    
    <div v-if="!loading" class="checkout-content">
      <!-- 结算信息为空 -->
      <div v-if="!checkoutItems || checkoutItems.length === 0" class="empty-checkout">
        <div class="empty-icon">
          <el-icon><ShoppingCart /></el-icon>
        </div>
        <div class="empty-text">购物车为空，快去选购商品吧！</div>
        <el-button type="primary" @click="goShopping" class="go-shopping-btn">
          去购物
        </el-button>
      </div>
      
      <!-- 结算表单 -->
      <div v-else class="checkout-form">
        <!-- 收货地址 -->
        <div class="checkout-section">
          <div class="section-title">
            <el-icon><MapLocation /></el-icon>
            <span>收货地址</span>
          </div>
          <div class="section-content">
            <div 
              v-if="addresses.length > 0"
              class="address-list"
            >
              <div 
                v-for="address in addresses"
                :key="address.id"
                class="address-item"
                :class="{ active: selectedAddressId === address.id }"
                @click="selectAddress(address.id)"
              >
                <div class="address-header">
                  <span class="recipient-name">{{ address.name }}</span>
                  <span class="recipient-phone">{{ address.phone }}</span>
                  <el-tag v-if="address.isDefault" type="primary" size="small">默认</el-tag>
                </div>
                <div class="address-detail">
                  {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}
                </div>
              </div>
            </div>
            <div v-else class="no-address">
              <div class="no-address-text">暂无收货地址，请添加</div>
              <el-button type="text" @click="addAddress">添加收货地址</el-button>
            </div>
            <div class="address-actions">
              <el-button type="primary" @click="addAddress">
                <el-icon><Plus /></el-icon>添加新地址
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 商品信息 -->
        <div class="checkout-section">
          <div class="section-title">
            <el-icon><Goods /></el-icon>
            <span>商品信息</span>
          </div>
          <div class="section-content">
            <div class="product-list">
              <div 
                v-for="item in checkoutItems"
                :key="item.id"
                class="product-item"
              >
                <div class="product-image">
                  <img :src="item.image" :alt="item.name" />
                </div>
                <div class="product-info">
                  <div class="product-name">{{ item.name }}</div>
                  <div class="product-specs">
                    <span v-for="(value, key) in item.specs" :key="key" class="spec-item">
                      {{ key }}：{{ value }}
                    </span>
                  </div>
                  <div class="product-price">¥{{ item.price }} x {{ item.quantity }}</div>
                </div>
                <div class="product-total">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 配送方式 -->
        <div class="checkout-section">
          <div class="section-title">
            <el-icon><Truck /></el-icon>
            <span>配送方式</span>
          </div>
          <div class="section-content">
            <div class="shipping-methods">
              <div 
                v-for="method in shippingMethods"
                :key="method.id"
                class="shipping-method-item"
                :class="{ active: selectedShippingMethod === method.id }"
                @click="selectShippingMethod(method.id)"
              >
                <div class="method-info">
                  <div class="method-name">{{ method.name }}</div>
                  <div class="method-desc">{{ method.description }}</div>
                </div>
                <div class="method-price">
                  {{ method.fee > 0 ? '¥' + method.fee.toFixed(2) : '免费' }}
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 支付方式 -->
        <div class="checkout-section">
          <div class="section-title">
            <el-icon><Wallet /></el-icon>
            <span>支付方式</span>
          </div>
          <div class="section-content">
            <div class="payment-methods">
              <div 
                v-for="method in paymentMethods"
                :key="method.id"
                class="payment-method-item"
                :class="{ active: selectedPaymentMethod === method.id }"
                @click="selectPaymentMethod(method.id)"
              >
                <div class="method-icon">
                  <i :class="method.icon"></i>
                </div>
                <div class="method-name">{{ method.name }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 优惠券 -->
        <div class="checkout-section">
          <div class="section-title">
            <el-icon><Ticket /></el-icon>
            <span>优惠券</span>
          </div>
          <div class="section-content">
            <div class="coupon-selection">
              <div class="coupon-summary">
                <span>已选择优惠：{{ selectedCoupon ? selectedCoupon.name : '无' }}</span>
                <span class="coupon-value">{{ selectedCoupon ? '-' + selectedCoupon.value : '' }}</span>
              </div>
              <el-button type="text" @click="selectCoupon">选择优惠券</el-button>
            </div>
          </div>
        </div>
        
        <!-- 订单备注 -->
        <div class="checkout-section">
          <div class="section-title">
            <el-icon><Edit /></el-icon>
            <span>订单备注</span>
          </div>
          <div class="section-content">
            <el-input
              v-model="orderRemark"
              type="textarea"
              placeholder="选填，填写订单备注信息"
              :rows="3"
              resize="none"
            />
          </div>
        </div>
      </div>
      
      <!-- 订单提交 -->
      <div v-if="checkoutItems && checkoutItems.length > 0" class="checkout-submit">
        <div class="submit-content">
          <div class="price-summary">
            <div class="price-item">
              <span>商品总价：</span>
              <span>¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="price-item">
              <span>运费：</span>
              <span>¥{{ shippingFee.toFixed(2) }}</span>
            </div>
            <div class="price-item discount">
              <span>优惠金额：</span>
              <span>-¥{{ discountAmount.toFixed(2) }}</span>
            </div>
            <div class="price-item total">
              <span>实付金额：</span>
              <span class="total-amount">¥{{ actualPayment.toFixed(2) }}</span>
            </div>
          </div>
          <div class="submit-actions">
            <el-button 
              type="primary" 
              @click="submitOrder"
              :loading="submitting"
              class="submit-btn"
              :disabled="!selectedAddressId || submitting"
            >
              {{ submitting ? '提交中...' : '提交订单' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-loading v-loading="loading" element-loading-text="加载中..." />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/modules/user'
import { useCartStore } from '../../store/modules/cart'
import { useOrderStore } from '../../store/modules/order'
import { ArrowRight, ShoppingCart, MapLocation, Plus, Goods, Wallet, Ticket, Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()
const orderStore = useOrderStore()

// 响应式数据
const loading = ref(true)
const submitting = ref(false)
const checkoutItems = ref([])
const addresses = ref([])
const selectedAddressId = ref('')
const selectedShippingMethod = ref('standard')
const selectedPaymentMethod = ref('alipay')
const selectedCoupon = ref(null)
const orderRemark = ref('')

// 配送方式
const shippingMethods = ref([
  {
    id: 'standard',
    name: '标准配送',
    description: '3-5个工作日送达',
    fee: 0
  },
  {
    id: 'express',
    name: '加急配送',
    description: '1-2个工作日送达',
    fee: 10
  },
  {
    id: 'same-day',
    name: '当日达',
    description: '当天17:00前下单，当天送达',
    fee: 20
  }
])

// 支付方式
const paymentMethods = ref([
  {
    id: 'alipay',
    name: '支付宝',
    icon: 'el-icon-alipay'
  },
  {
    id: 'wechat',
    name: '微信支付',
    icon: 'el-icon-wechat'
  },
  {
    id: 'bank',
    name: '银行卡支付',
    icon: 'el-icon-credit-card'
  }
])

// 计算属性：商品总价
const totalPrice = computed(() => {
  return checkoutItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

// 计算属性：运费
const shippingFee = computed(() => {
  const method = shippingMethods.value.find(m => m.id === selectedShippingMethod.value)
  return method ? method.fee : 0
})

// 计算属性：优惠金额
const discountAmount = computed(() => {
  return selectedCoupon ? selectedCoupon.value : 0
})

// 计算属性：实际支付金额
const actualPayment = computed(() => {
  return Math.max(0, totalPrice.value + shippingFee.value - discountAmount.value)
})

// 去购物
const goShopping = () => {
  router.push('/')
}

// 选择地址
const selectAddress = (addressId) => {
  selectedAddressId.value = addressId
}

// 添加地址
const addAddress = () => {
  router.push('/user/address')
}

// 选择配送方式
const selectShippingMethod = (methodId) => {
  selectedShippingMethod.value = methodId
}

// 选择支付方式
const selectPaymentMethod = (methodId) => {
  selectedPaymentMethod.value = methodId
}

// 选择优惠券
const selectCoupon = () => {
  ElMessage.info('选择优惠券功能待实现')
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  
  submitting.value = true
  try {
    // 构建订单数据
    const orderData = {
      addressId: selectedAddressId.value,
      paymentMethod: selectedPaymentMethod.value,
      shippingMethod: selectedShippingMethod.value,
      couponId: selectedCoupon ? selectedCoupon.id : null,
      remark: orderRemark.value,
      items: checkoutItems.value.map(item => ({
        productId: item.productId,
        quantity: item.quantity,
        specs: item.specs
      }))
    }
    
    // 模拟提交订单，实际项目中应调用 orderStore.submitOrder(orderData)
    // const { orderId } = await orderStore.submitOrder(orderData)
    
    // 模拟创建订单ID
    const orderId = 'ORD' + Date.now()
    
    // 跳转到支付页面
    router.push(`/payment/${orderId}`)
    
  } catch (error) {
    ElMessage.error('提交订单失败：' + error.message)
    console.error('提交订单失败：', error)
  } finally {
    submitting.value = false
  }
}

// 加载结算数据
const loadCheckoutData = async () => {
  loading.value = true
  try {
    // 检查用户是否登录
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    // 加载购物车结算商品
    // const items = cartStore.getCheckoutItems()
    // checkoutItems.value = items.length > 0 ? items : cartStore.getCartItems()
    
    // 模拟购物车结算数据
    checkoutItems.value = generateMockCheckoutItems()
    
    // 加载收货地址
    // const userAddresses = await userStore.getUserAddresses()
    // addresses.value = userAddresses
    
    // 模拟收货地址数据
    addresses.value = generateMockAddresses()
    
    // 设置默认地址
    const defaultAddress = addresses.value.find(addr => addr.isDefault)
    if (defaultAddress) {
      selectedAddressId.value = defaultAddress.id
    } else if (addresses.value.length > 0) {
      selectedAddressId.value = addresses.value[0].id
    }
    
  } catch (error) {
    ElMessage.error('加载结算数据失败：' + error.message)
    console.error('加载结算数据失败：', error)
  } finally {
    loading.value = false
  }
}

// 生成模拟结算商品数据
const generateMockCheckoutItems = () => {
  return [
    {
      id: 1,
      productId: 1,
      name: '超级智能手机 Pro Max',
      image: '/product/hot1.png',
      price: 6999,
      quantity: 1,
      specs: { '颜色': '暗夜黑', '内存': '8GB+256GB' }
    },
    {
      id: 3,
      productId: 4,
      name: '无线蓝牙耳机 Pro',
      image: '/product/hot4.png',
      price: 1299,
      quantity: 2,
      specs: { '颜色': '白色' }
    }
  ]
}

// 生成模拟收货地址数据
const generateMockAddresses = () => {
  return [
    {
      id: 1,
      name: '张三',
      phone: '138****1234',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detailAddress: '科技园南区8栋101室',
      isDefault: true
    },
    {
      id: 2,
      name: '张三',
      phone: '138****1234',
      province: '广东省',
      city: '广州市',
      district: '天河区',
      detailAddress: '天河路385号太古汇',
      isDefault: false
    }
  ]
}

// 组件挂载时加载数据
onMounted(() => {
  loadCheckoutData()
})
</script>

<style scoped>
.checkout-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* 面包屑导航 */
.breadcrumb-section {
  margin: 20px 0;
}

/* 页面标题 */
.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: $font-size-xxl;
  color: $text-color;
  font-weight: bold;
  margin: 0;
}

/* 结算内容 */
.checkout-content {
  margin-bottom: 30px;
}

/* 结算表单为空 */
.empty-checkout {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 40px;
}

.empty-icon {
  font-size: 80px;
  color: $text-color-placeholder;
  margin-bottom: 20px;
}

.empty-text {
  font-size: $font-size-base;
  color: $text-color-secondary;
  margin-bottom: 20px;
}

.go-shopping-btn {
  padding: 10px 30px;
  font-size: $font-size-base;
}

/* 结算表单 */
.checkout-form {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  overflow: hidden;
}

/* 结算区块 */
.checkout-section {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 20px;
  font-size: $font-size-lg;
  color: $text-color;
  font-weight: 500;
  background-color: $fill-color;
  border-bottom: 1px solid $border-color;
}

.section-content {
  padding: 20px;
}

/* 收货地址 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 15px;
}

.address-item {
  padding: 20px;
  border: 2px solid $border-color;
  border-radius: $border-radius-base;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: $primary-color;
  box-shadow: 0 0 0 2px $primary-color-light;
}

.address-item.active {
  border-color: $primary-color;
  background-color: $primary-color-light;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.recipient-name {
  font-size: $font-size-base;
  color: $text-color;
  font-weight: 500;
}

.recipient-phone {
  font-size: $font-size-base;
  color: $text-color-secondary;
}

.address-detail {
  font-size: $font-size-base;
  color: $text-color;
  line-height: 1.5;
}

.no-address {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40px 20px;
  text-align: center;
  border: 1px dashed $border-color;
  border-radius: $border-radius-base;
  margin-bottom: 15px;
}

.no-address-text {
  font-size: $font-size-base;
  color: $text-color-secondary;
}

.address-actions {
  text-align: center;
}

/* 商品信息 */
.product-list {
  border: 1px solid $border-color;
  border-radius: $border-radius-base;
  overflow: hidden;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border-bottom: 1px solid $border-color;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 100px;
  height: 100px;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: $border-radius-base;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: $font-size-base;
  color: $text-color;
  margin-bottom: 10px;
}

.product-specs {
  margin-bottom: 10px;
}

.spec-item {
  display: inline-block;
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin-right: 15px;
  margin-bottom: 5px;
}

.product-price {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.product-total {
  font-size: $font-size-base;
  color: $text-color;
  font-weight: 500;
}

/* 配送方式 */
.shipping-methods {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.shipping-method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border: 2px solid $border-color;
  border-radius: $border-radius-base;
  cursor: pointer;
  transition: all 0.3s;
}

.shipping-method-item:hover {
  border-color: $primary-color;
  box-shadow: 0 0 0 2px $primary-color-light;
}

.shipping-method-item.active {
  border-color: $primary-color;
  background-color: $primary-color-light;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: $font-size-base;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 5px;
}

.method-desc {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.method-price {
  font-size: $font-size-base;
  color: $text-color;
}

/* 支付方式 */
.payment-methods {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.payment-method-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 30px;
  border: 2px solid $border-color;
  border-radius: $border-radius-base;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method-item:hover {
  border-color: $primary-color;
  box-shadow: 0 0 0 2px $primary-color-light;
}

.payment-method-item.active {
  border-color: $primary-color;
  background-color: $primary-color-light;
}

.method-icon {
  font-size: $font-size-xl;
  color: $primary-color;
}

/* 优惠券 */
.coupon-selection {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border: 1px solid $border-color;
  border-radius: $border-radius-base;
}

.coupon-summary {
  display: flex;
  align-items: center;
  gap: 15px;
}

.coupon-value {
  color: $danger-color;
  font-weight: 500;
}

/* 订单提交 */
.checkout-submit {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 20px;
  margin-bottom: 30px;
}

.submit-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  flex-wrap: wrap;
  gap: 30px;
}

.price-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
  font-size: $font-size-base;
  color: $text-color;
}

.price-item.discount {
  color: $danger-color;
}

.price-item.total {
  font-size: $font-size-lg;
  font-weight: 500;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid $border-color;
}

.total-amount {
  font-size: $font-size-xxl;
  color: $danger-color;
  font-weight: bold;
}

.submit-actions {
  display: flex;
  gap: 10px;
}

.submit-btn {
  padding: 12px 48px;
  font-size: $font-size-lg;
  background-color: $danger-color;
  border-color: $danger-color;
}

.submit-btn:hover {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.submit-btn:disabled {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: $text-color-placeholder;
}

/* 加载状态 */
.loading-container {
  min-height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  /* 保持现有样式 */
}

@media (max-width: 992px) {
  .submit-content {
    flex-direction: column-reverse;
    align-items: stretch;
    gap: 20px;
  }
  
  .submit-actions {
    justify-content: center;
  }
  
  .price-summary {
    align-self: center;
  }
}

@media (max-width: 768px) {
  .checkout-container {
    padding: 0 10px;
  }
  
  .section-title,
  .section-content {
    padding: 15px;
  }
  
  .address-item {
    padding: 15px;
  }
  
  .product-item {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px;
    gap: 15px;
  }
  
  .product-image {
    width: 80px;
    height: 80px;
  }
  
  .payment-methods {
    flex-direction: column;
    gap: 10px;
  }
  
  .payment-method-item {
    width: 100%;
  }
  
  .checkout-submit {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: $font-size-xl;
  }
  
  .empty-checkout {
    padding: 20px;
  }
  
  .empty-icon {
    font-size: 60px;
  }
  
  .section-title {
    font-size: $font-size-base;
  }
  
  .shipping-method-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .price-item {
    font-size: $font-size-sm;
    gap: 15px;
  }
  
  .price-item.total {
    font-size: $font-size-base;
  }
  
  .total-amount {
    font-size: $font-size-xl;
  }
  
  .submit-btn {
    width: 100%;
    padding: 12px 24px;
    font-size: $font-size-base;
  }
}
</style>